package com.sunseagear.common.base.mvc.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunseagear.common.base.mvc.convert.DateConvertEditor;
import com.sunseagear.common.base.mvc.convert.LocalDateConvertEditor;
import com.sunseagear.common.base.mvc.convert.LocalDateTimeConvertEditor;
import com.sunseagear.common.base.mvc.convert.StringConvertEditor;
import com.sunseagear.common.utils.ServletUtils;
import com.sunseagear.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Objects;

public abstract class BaseBeanController {

    /**
     * 日志对象
     */
    protected final Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 初始化数据绑定
     */
    @InitBinder
    void initBinder(ServletRequestDataBinder binder) {
        // 将所有传递进来的String进行HTML编码，防止XSS攻击
        // 这个会导致数据库数据
        binder.registerCustomEditor(String.class, new StringConvertEditor());
        // 日期格式
        binder.registerCustomEditor(Date.class, new DateConvertEditor());
        binder.registerCustomEditor(LocalDate.class, new LocalDateConvertEditor());
        binder.registerCustomEditor(LocalDateTime.class, new LocalDateTimeConvertEditor());
    }

    public <T> Page<T> getPage() {
        String page = Objects.requireNonNull(ServletUtils.getRequest()).getParameter("page");
        String limit = ServletUtils.getRequest().getParameter("limit");
        int pageInt = !StringUtils.isEmpty(page) ? Integer.parseInt(page) : 1;
        int limitInt = !StringUtils.isEmpty(limit) ? Integer.parseInt(limit) : 20;
        return new Page<T>(pageInt, limitInt);
    }

}
